//
//  DDAlertView.m
//  ICBCSuisseCredit
//
//  Created by zhangjingle on 2017/4/13.
//  Copyright © 2017年 Victor. All rights reserved.
//

#import "DDAlertView.h"
#import "UIView+Frame.h"
//#import "DDAlertManager.h"
//加载 自定义VIEW nib 文件
//获取当前屏幕宽度，高度
#define kSCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define kSCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
#define LOADXIBVIEW(index) [[NSBundle mainBundle] loadNibNamed:[[self class]description] owner:self options:nil][index]
#define HDkeyWindow [UIApplication sharedApplication].keyWindow
//分割线 - (通用)
#define kLineSeprate kSetColor(221,221,221)
//RGB颜色数值设置,设定特殊颜色
#define kSetColor(rd,ge,be) ([UIColor colorWithRed:rd/255.0 green:ge/255.0 blue:be/255.0 alpha:1])
typedef enum {
    AlertType_normal,//普通,一个按钮
    AlertType_action,//有点击事件,2个按钮
    AlertType_password,//有密码输入框
    AlertType_description, //有原文描述
    AlertType_closeAction
    
}DDAlertType;

@interface DDAlertView()<UITextFieldDelegate>
{
    void (^ _clickLeft)();
    void (^ _clickRight)();
    void (^ _clickRightPassword)(NSString * password);
}

@property (nonatomic) DDAlertType alertType;

@property (nonatomic, strong) UIView * customView;

@property (nonatomic, strong) IBOutlet UILabel * title;
@property (nonatomic, strong) IBOutlet UILabel * message;
@property (nonatomic, strong) IBOutlet UIView * bottomView;
@property (nonatomic, strong) IBOutlet UIButton * btn_left;
@property (nonatomic, strong) IBOutlet UIButton * btn_right;
@property (nonatomic, strong) IBOutlet UILabel * line;

@property (nonatomic, strong) IBOutlet UITextField * TF_password;

@property (nonatomic, strong) UIView * mask;
@property (nonatomic) BOOL isShow;
@property (strong, nonatomic) IBOutlet UIButton *closeBtn;//关闭按钮
@property (nonatomic,assign)BOOL isShowForView;//是否添加到view层

@end

@implementation DDAlertView

/*!@brief ****  初始化 一个按钮  */
-(id)initWithTitle:(NSString *)title message:(NSString *)message btnName:(NSString *)btnName finished:(void(^)())onFinished
{
    self = [super init];
    if (self) {
        [self createCusotmView];
        
        [self setupType:AlertType_normal
                  title:title
                message:message
               leftName:btnName
              rightName:nil
              clickLeft:onFinished
             clickRight:nil
          clickPassword:nil];
    }
    return self;
}

/*!@brief ****  初始化 2个按钮 */
-(id)initCloseWithTitle:(NSString *)title close:(NSString *)close message:(NSString *)message leftName:(NSString *)leftName rightName:(NSString *)rightName clickLeft:(void(^)())clickLeft clickRight:(void(^)())clickRight;
{
    self = [super init];
    if (self) {
        [self createCusotmView];
        if([close isEqualToString:@"closeAction"]){
            self.closeBtn.hidden = NO;
        }
        [self setupType:AlertType_action
                  title:title
                message:message
               leftName:leftName
              rightName:rightName
              clickLeft:clickLeft
             clickRight:clickRight
          clickPassword:nil];
    }
    return self;
}

/*!@brief ****  初始化 2个按钮 有密码输入框 */
-(id)initPasswordWithTitle:(NSString *)title leftName:(NSString *)leftName rightName:(NSString *)rightName clickLeft:(void(^)())clickLeft clickRight:(void(^)(NSString * password))clickRight
{
    self = [super init];
    if (self) {
        
        [self createCusotmView];
        [self setupType:AlertType_password
                  title:title
                message:nil
               leftName:leftName
              rightName:rightName
              clickLeft:clickLeft
             clickRight:nil
          clickPassword:clickRight];
    }
    return self;
}
/*!@brief ****  初始化 2个按钮 有描述输入框 */
-(id)initDescriptionWithTitle:(NSString *)title leftName:(NSString *)leftName rightName:(NSString *)rightName clickLeft:(void(^)())clickLeft clickRight:(void(^)(NSString * description))clickRight
{
    self = [super init];
    if (self) {
        
        [self createCusotmView];
        [self setupType:AlertType_description
                  title:title
                message:nil
               leftName:leftName
              rightName:rightName
              clickLeft:clickLeft
             clickRight:nil
          clickPassword:clickRight];
    }
    return self;
}
-(void)createCusotmView
{
    
    self.frame = CGRectMake(0, 0, 235, 136);
    self.backgroundColor = [UIColor clearColor];
    
    self.customView = LOADXIBVIEW(0);
    self.closeBtn.hidden = YES;
    self.customView.layer.masksToBounds = YES;
    self.customView.layer.cornerRadius = 5;
    
    [self addSubview:self.customView];
}

-(void)layoutSubviews
{
    float per = kSCREEN_WIDTH/320;
    CGFloat width = per * self.frame.size.width;
    CGFloat height = per * self.frame.size.height;
    self.frame = CGRectMake(0, 0, width, height);
    
    self.customView.frame = CGRectMake(0, 0, width, height);
    
    self.btn_left.left = 0;
    self.btn_left.width = (self.alertType == AlertType_normal)?self.customView.frame.size.width:self.customView.frame.size.width/2;
    
    self.btn_right.left = self.customView.width/2;
    self.btn_right.width = self.customView.width/2;
    self.line.left = self.customView.width/2;

    self.center = HDkeyWindow.center;
    
    if (self.alertType == AlertType_password) {
        self.centerY = HDkeyWindow.center.y - 226/2;
        self.TF_password.layer.masksToBounds = YES;
        self.TF_password.layer.borderWidth = 0.5;
        self.TF_password.placeholder = @"请输入密码";
        self.TF_password.tag = 201888;
        self.TF_password.secureTextEntry=YES;
        self.TF_password.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        self.TF_password.layer.borderColor = kLineSeprate.CGColor;
        [self.TF_password becomeFirstResponder];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector (textFieldChange:)
                                                    name:UITextFieldTextDidChangeNotification object:self.TF_password];

    }
    /*!@brief ****   ICBC_IO原文描述类弹框 */
    if(self.alertType == AlertType_description) {
        self.centerY = HDkeyWindow.center.y - 226/2;
        self.TF_password.layer.masksToBounds = YES;
        self.TF_password.layer.borderWidth = 0.5;
        self.TF_password.placeholder = @"请输入原文描述";
        self.TF_password.tag = 201999;
        self.TF_password.keyboardType =UIKeyboardTypeDefault;
        self.TF_password.layer.borderColor = kLineSeprate.CGColor;
        [self.TF_password becomeFirstResponder];
        self.title.font = [UIFont systemFontOfSize:10];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector (textFieldChange:)
                                                    name:UITextFieldTextDidChangeNotification object:self.TF_password];
    }
    
    //文字高度自适应
    if (self.alertType != AlertType_password || self.alertType != AlertType_description){
        CGFloat maxheight = HDkeyWindow.size.height -50*2 - (self.customView.frame.size.height - self.message.frame.size.height);
        CGSize size = [self calculateSizeWith:self.message.text font:self.message.font with:self.message.width with:maxheight];
        if (size.height > self.message.frame.size.height) {
            CGFloat differ = size.height - self.message.frame.size.height + 6;
            self.frame = CGRectMake(0, 0, width, height + differ);
            self.customView.frame = CGRectMake(0, 0, width, height + differ);
            
            CGRect msgFrame = self.message.frame;
            self.message.frame = CGRectMake(msgFrame.origin.x, msgFrame.origin.y - differ/2, msgFrame.size.width, msgFrame.size.height + differ);
            
            self.center = HDkeyWindow.center;

            
        }
    }
    //当alert显示到View层时，需要调整alert的y值，带导航的需要将弹框偏移64像素
    if(self.isShowForView){
        self.y = self.y- 64;
    }
    
    
}

//设置label宽度
- (CGSize)calculateSizeWith:(NSString *)str font:(UIFont*)font with:(CGFloat)width with:(CGFloat)height
{
    CGSize size1 = CGSizeMake(width, height);
    //获取当前文本的属性
    NSDictionary *tdic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
    CGSize labelSize = [str boundingRectWithSize:size1 options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:tdic context:nil].size;
    return labelSize;
}

- (void) textFieldChange:(NSNotification *)notification{
    UITextField *textField=[notification object];
    if(textField.tag == 201888){
        if(textField.text.length>=8)
        {
            textField.text = [textField.text substringWithRange:(NSMakeRange(0, 8))];
        }
    }
}
-(void)setupType:(DDAlertType)alertType title:(NSString *)title message:(NSString *)message leftName:(NSString *)leftName rightName:(NSString *)rightName clickLeft:(void(^)())clickLeft clickRight:(void(^)())clickRight clickPassword:(void(^)(NSString * password))clickRightPassword
{
    self.alertType = alertType;
    self.title.text = (title)?title:@"温馨提示";
    self.message.text = message;
    if([self.message.text containsString:@"请核对扫描结果"] || [self.message.text containsString:@"(超级现现金快线等日结产品除外)"]){
        self.message.textAlignment = NSTextAlignmentLeft;
    }else{
        self.message.textAlignment = NSTextAlignmentCenter;
    }
    
    [self.btn_left setTitle:(leftName)?leftName:@"取消" forState:UIControlStateNormal];
    [self.btn_right setTitle:(rightName)?rightName:@"确定" forState:UIControlStateNormal];
    
    if (alertType == AlertType_normal) {
        self.line.hidden = YES;
        self.btn_right.hidden = YES;
        self.btn_left.width = self.customView.width;
        [self.btn_left setTitle:(leftName)?leftName:@"确定" forState:UIControlStateNormal];
    }
    
    if (self.alertType == AlertType_password || self.alertType == AlertType_description) {
        self.message.hidden = YES;
        self.TF_password.hidden = NO;
    }else{
        self.message.hidden = NO;
        self.TF_password.hidden = YES;
    }
    
    if (clickLeft) {
        _clickLeft = [clickLeft copy];
    }
    if (clickRight) {
        _clickRight = [clickRight copy];
    }
    if (clickRightPassword) {
        _clickRightPassword = [clickRightPassword copy];
    }
}
-(IBAction)onClickedLeft:(id)sender
{
    if (_clickLeft) {
        _clickLeft();
    }
    if(self.title.text.length >= 3 && [self.title.text isEqualToString:@"提示 "]){
        
    }else{
        [self dismiss];
        }
}

-(IBAction)onClickedRight:(id)sender
{
    if (self.alertType == AlertType_password || self.alertType == AlertType_description) {
        if (_clickRightPassword) {
            _clickRightPassword(self.TF_password.text);
        }
    }else{
        if (_clickRight) {
            _clickRight();
        }
    }
    [self dismiss];
}
#pragma mark - 关闭弹框
- (IBAction)closeAction:(id)sender {
    [self dismiss];
}

-(void)createMask
{
    self.mask = [[UIView alloc] initWithFrame:HDkeyWindow.bounds];
    self.mask.backgroundColor = [UIColor blackColor];
    self.mask.alpha = 0.4;
//    UITapGestureRecognizer * tapGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
//    [self.mask addGestureRecognizer:tapGes];
}
//
//- (void)tapAction:(UIGestureRecognizer *)gestureRecognizer
//{
//    [self dismiss];
//}
-(void)removeMask
{
    [self.mask removeFromSuperview];
    self.mask = nil;
}
/*!@brief ****  添加到Window上  */
-(void)show{
    [self resignFirstResponder];
    [self createMask];
    
    dispatch_async(dispatch_get_main_queue(),^{
    [HDkeyWindow addSubview:self.mask];
    [HDkeyWindow addSubview:self];
    
});
    
}
/*!@brief ****  添加到指定视图上  */
- (void)showForView:(UIView *)view
{
    [self resignFirstResponder];
    [self createMask];
    [view addSubview:self.mask];
    self.isShowForView = YES;
    [view addSubview:self];
    
}

-(void)dismiss
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self removeMask];
    [self removeFromSuperview];
}

//-(void)show
//{
//    [CommonUtil hideKeyBoard];
//    if ([DDAlertManager shared].alerts.count == 0) {
//        [self createMask];
//        [HDkeyWindow addSubview:self.mask];
//    }
//    [HDkeyWindow addSubview:self];
//    [[DDAlertManager shared] onShow:self];
//}
//
//-(void)dismiss
//{
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//    
//    if ([DDAlertManager shared].alerts.count <= 1){
//        [self removeMask];
//    }
//    [self removeFromSuperview];
//    [[DDAlertManager shared] onDissmiss:self];
//    
//}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self resignFirstResponder];
    [self onClickedRight:nil];
    return YES;
}

@end
